import * as api from '@/services/deploy';
import {
  EditOutlined,
  PlusOutlined,
  RedoOutlined,
} from '@ant-design/icons';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  Checkbox,
  Popconfirm,
  Space,
  Tag,Tooltip,
  // Typography 
} from 'antd';
// const { Paragraph } = Typography;
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';
import * as utils from '@/utils/utils';
// import CheckTaskReportForm from '../CheckTask/CheckReportForm';
// import EventReportForm from '../IdcApiEvent/ReportForm';
// import CheckTaskStatusTag from '@/components/CheckTaskStatusTag';
// import IdcApiEventStatusTag from '@/components/IdcApiEventStatusTag';
import DeployLogStatusTag from '@/components/DeployLogStatusTag';
import Countdown from 'antd/es/statistic/Countdown';
import VpnServerForm from '../VpnServer/components/VpnServerForm';
import * as c from '@/services/consts';

type DeployReportFormProps = {
  visible: boolean;
  current: API.Deploy | undefined;
  onCancel: () => void;
  onSubmit: () => void;
};

const DeployReportForm: React.FC<DeployReportFormProps> = (props) => {
  const { visible, onCancel,onSubmit,  current } = props;

  if (!visible) {
    return null;
  }

  let tableGroupTitle: string = '';
  let tableGroupFont: string = 'normal';

  const { hasRight } = useModel('useAuthModel');
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  // const [formCheckTaskReportVisible, setFormCheckTaskReportVisible] =useState<boolean>(false);
  // const [currentTaskVer, setCurrentTaskVer] = useState<string | undefined>(undefined);
  // const [formEventReportVisible, setFormEventReportVisible] =useState<boolean>(false);
  // const [currentEventVer, setCurrentEventVer] = useState<string | undefined>(undefined);
  const [countdownTicks, setCountdownTicks] = useState<number>(Date.now() + 30000,);
  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [currentNodeId, setCurrentNodeId] = useState<string | undefined>(
    undefined,
  );
  const [displayOnlyError, setDisplayOnlyError] = useState<boolean>(false);

  const {
    setDeployConfigPublish,getDeployConfigOptions
  } = useModel('useGlobalModel', (model) => ({
    setDeployConfigPublish: model.setDeployConfigPublish,
    getDeployConfigOptions: model.getDeployConfigOptions,
  }));


  const reload = () => {
    actionRef.current?.reload();
    setCountdownTicks(Date.now() + 30000);
  };

  const handleRemoves = async (keys:any[]) => {
    const result = await api.removeLogs({keys});
    if (result && result.success) {
      actionRef?.current?.clearSelected();
      actionRef?.current?.reload();
    }
  };

  const handleRedo = async (keys:any[]) => {
    const result = await api.redo({keys});
    if (result && result.success) {
      onSubmit();
    }
  };

  const getLastLines = (str:string|undefined, line: number) => {
    if(!str) return [];
    const lines = str.split('\n');
    return lines.slice(-line);
  };
  
  const getActionOptions = () => {
    let options = getDeployConfigOptions(1);
    return options.map((element) => {
      return {label:element.label, value: element.value};
    });
  }
  
  const logColumns: ProColumns<API.DeployLog>[] = [
    {
      title: '分组',
      dataIndex: 'groupNames',
      width: 300,
      render: (_, record) => {
        let text = record.groupNames?.map((val)=>val).join(',');
        if (tableGroupTitle != text) {
          tableGroupFont = tableGroupFont == 'blue' ? 'green' : 'blue';
        }
        tableGroupTitle = text;
        return (<div>
        <div style={{marginBottom:5}}><DeployLogStatusTag status={record.status} /></div>
          <div style={{ color: tableGroupFont }}>
            {record.instanceId} [{record.serverName}]
            <a onClick={(e) => {
                  if(record.serverId){
                    setFormVisible(true);
                    setCurrentNodeId(record.serverId);
                  }
                }}
              >{' '}<EditOutlined /></a>
            </div>
          <div style={{ color: tableGroupFont }}>{text}</div>
        <div><PlusOutlined /> {utils.formatDate(record.createTime)}</div>
        <div>{record.endTime ? <><RedoOutlined /> {utils.formatDate(record.endTime)}</> : ''}</div>
        </div>);
      },
    },
    {
      title: '执行结果',
      dataIndex: 'reports',
      // width:500,
      render: (_, record) => {
        
          return <>
          
          <Tooltip overlayStyle={{minWidth:600, maxWidth: 900}} title={<div>
              <div style={{maxWidth:900, maxHeight:600, overflow:'auto'}}>
                {getLastLines(record.stdout, 100000)?.map((c)=><div>{c}</div>)}
            </div></div>}>
            {getLastLines(record.stdout, 5).map((val)=><div>{val}</div>)}
          </Tooltip>
            {/* {record.reports?.length > 0 ? <Tag color='error'><b>被墙：{record.reports?.length} </b></Tag> : ''} */}

            {/* {record.tasks?.length > 0 ? record.tasks?.map((val) => { return <div>
              <a
                onClick={(e) => {
                  setFormCheckTaskReportVisible(true);
                  setCurrentTaskVer(val.id);
                }}
              >
                <Tag color='cyan' style={{width:50}}>检测</Tag><b>{val.id}</b> [{utils.formatDate(val.createTime)}
                ] <CheckTaskStatusTag status={val.status} />
              </a>
            </div>}) : ''} */}

          {/* {record.events?.length > 0 ? record.events?.map((val) => { return <div>
            <a
              onClick={(e) => {
                setFormEventReportVisible(true);
                setCurrentEventVer(val.id);
              }}
            >
              <Tag color='blue'>更换IP</Tag><b>{val.id}</b> [{utils.formatDate(val.createTime)}
              ] <IdcApiEventStatusTag status={val.status} />
            </a>
          </div>}) : ''} */}


            </>
      },
    },
  ];

  return (
    <DrawerForm
      open={visible}
      title={
        <>
          执行记录 <Tag color="blue">版本：{current?.id}</Tag>{' '}
          {current?.name ? <Tag color="blue">名称：{current?.name}</Tag> : ''}
          <Tag color="orange">{c.getObjectText(getActionOptions(), current?.action)}</Tag>
        </>
      }
      formRef={formRef}
      autoFocusFirstInput
      width={1200}
      // onFinish={handleFormSubmit}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        maskClosable: false,
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [defaultDoms[0]];
        },
      }}
    >

      <ProTable<API.DeployLog>
        headerTitle={<div style={{width:850}}>
          <div>
          <Checkbox onChange={(e) => { setDisplayOnlyError(e.target.checked);}} checked={displayOnlyError}>仅出错项</Checkbox>          
          </div>
        </div>}
        rowKey="id"
        actionRef={actionRef}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        search={false}
        columns={logColumns}
        expandable={undefined}
        rowSelection={{
          defaultSelectedRowKeys: [],
          // onChange: (selectedRowKeys, selectedRows) => {
          //   setSelectIds(selectedRowKeys);
          // },
        }}
        
        toolBarRender={() => {
          var toolbarDoms: any[] = [];
          toolbarDoms.push([
            <span>
            <Countdown
              title=""
              key="cdRefresh"
              value={countdownTicks}
              format="s"
              prefix=""
              suffix="秒后刷新"
              valueStyle={{
                fontSize: 14,
                color: 'gray',
              }}
              onFinish={reload}
            />
          </span>
          ]);

          return toolbarDoms;
        }}
        tableAlertRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 条记录
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消
              </a>
            </span>
            
            <span>
              {hasRight('checkschedule_create') ?
                  <Popconfirm
                    key="check_redo"
                    title="确定要重新操作吗?"
                    onConfirm={async () => {
                      await handleRedo(selectedRowKeys);
                    }}
                  >
                    <a>重新操作</a>
                  </Popconfirm>
                : ''
              }
            </span>

            <span>
              {hasRight('checkschedule_delete') ?
                  <Popconfirm
                    key="check_delete"
                    title="确定要删除吗?"
                    onConfirm={async () => {
                      await handleRemoves(selectedRowKeys);
                    }}
                  >
                    <a>删除</a>
                  </Popconfirm>
                : ''
              }
            </span>
          </Space>
        )}
        params={{
          deployId: current?.id,
          displayOnlyError,
        }}
        request={api.logs}
        pagination={{
          defaultPageSize: 50,
          pageSizeOptions: [
            '50',
            '100',
            '200',
            '300',
          ],
          hideOnSinglePage: false,
        }}
      />
      
      <VpnServerForm
        visible={formVisible}
        loadNodeId={currentNodeId}
        defaultGroupIds={undefined}
        onSubmit={() =>{
          setDeployConfigPublish(true);
          setCurrentNodeId(undefined);
          setFormVisible(false);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setFormVisible(false);
          setCurrentNodeId(undefined);
        }}
      />

      {/* <CheckTaskReportForm
        visible={formCheckTaskReportVisible}
        ver={currentTaskVer}
        groupId={undefined}
        onCancel={() => {
          setFormCheckTaskReportVisible(false);
          setCurrentTaskVer(undefined);
        }}
        onCancelAndReload={() => {
          setFormCheckTaskReportVisible(false);
          setCurrentTaskVer(undefined);
          // actionRef.current?.reload();
        }}
      />
      <EventReportForm
        visible={formEventReportVisible}
        ver={currentEventVer}
        onCancel={() => {
          setFormEventReportVisible(false);
          setCurrentEventVer(undefined);
        }}
      /> */}



    </DrawerForm>
  );
};

export default DeployReportForm;
